import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef, Optional, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { ActivatedRoute } from '@angular/router';
import { TableComponent } from '@shared/components/table/table.component';
import { TableConfig } from '@shared/models/table/table-config.models';
import { DemoUser } from './table-mock-data';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { ItemComponent } from '@shared/components/table/item.component';

/**
 * 表格组件演示页面
 * 
 * 同时作为页面组件（显示表格）和表单组件（用于添加对话框）
 * 从路由解析器获取表格配置并传递给 TableComponent
 */
@Component({
  selector: 'app-table-demo',
  standalone: true,
  imports: [
    CommonModule,
    MatCardModule,
    ReactiveFormsModule,
    // @ts-expect-error - TableComponent has protected constructor from PageComponent, but it's still usable as standalone component
    TableComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './table-demo.component.html',
  styleUrls: ['./table-demo.component.scss']
})
export class TableDemoComponent extends ItemComponent<DemoUser> implements OnInit {

  constructor(
    fb: FormBuilder,
    cd: ChangeDetectorRef,
    private route: ActivatedRoute,
    // 通过注入器检查是否在对话框模式下（对话框会通过注入器提供 'tableConfig' 和 'item'）
    @Optional() @Inject('tableConfig') private injectedTableConfig?: TableConfig<DemoUser>,
    @Optional() @Inject('item') private injectedItem?: DemoUser
  ) {
    super(fb, cd);
    
    // 如果是对话框模式，设置 tableConfig 和 item
    if (this.injectedTableConfig) {
      this.tableConfig = this.injectedTableConfig;
    }
    if (this.injectedItem !== undefined) {
      this.item = this.injectedItem;
    }
  }

  override ngOnInit(): void {
    // 只有在对话框模式下（通过注入器提供了 tableConfig）时才初始化表单
    // 页面模式下不创建 itemForm，避免显示表单
    if (this.injectedTableConfig) {
      // 对话框模式：调用父类初始化创建表单
      super.ngOnInit();
    }
    // 页面模式：不调用 super.ngOnInit()，保持 itemForm 为 undefined
  }

  // 表单组件方法：用于添加对话框
  buildForm(item: DemoUser): FormGroup {
    return this.fb.group({
      name: [item?.name || '', [Validators.required, Validators.minLength(2)]],
      email: [item?.email || '', [Validators.required, Validators.email]],
      role: [item?.role || '用户', Validators.required],
      status: [item?.status || 'active', Validators.required]
    });
  }

  updateForm(item: DemoUser): void {
    if (item && this.itemForm) {
      this.itemForm.patchValue({
        name: item.name || '',
        email: item.email || '',
        role: item.role || '用户',
        status: item.status || 'active'
      });
    }
  }
}
